package com.ciwong.epaper.modules.pad.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.NoConnectionError;
import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.pad.listener.KeyboardChangeListener;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;

/**
 * Created by Administrator on 2017/7/12.
 */
public class PadRetrievePwdActivity extends Activity implements View.OnClickListener {


	//    private ViewGroup mContentView;
	private TextView mTvGetIndentifyCode;
	private TextView mTvNext;
	private EditText mEtNumber;
	private EditText mEtIdentifyCode;
	private int currentCount = 60;
	private final int ERR_CODE_BIND_OTHER_PHONE = 60001;
	private final int ERR_CODE_UNBIND           = 60002;//未绑定手机号
	private final int ERR_CODE_ERR             = 80002;
	private final int     MESSAGE_COUNTDOWN = 1;
	private       Handler mHandler          = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MESSAGE_COUNTDOWN:
					//60秒倒计时
					countdown();
					break;
			}
		}
	};
	private String mPhonenumber;
	private int    screenHeight;
	// 软件盘弹起后所占高度阀值
	private int keyHeight = 0;
	private KeyboardChangeListener mKeyboardChangeListener;
	private KeyboardLayout         keyboardLay;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_pad_retrieve_pwd_dialog);
		setFinishOnTouchOutside(false);
		//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
		//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
		initView();
		initEvent();

	}




	private void initView() {
		mTvGetIndentifyCode = (TextView) findViewById(R.id.tv_get_identify_code);
		mTvNext = (TextView) findViewById(R.id.tv_next);
		mEtNumber = (EditText) findViewById(R.id.et_login_number);
		mEtIdentifyCode = (EditText) findViewById(R.id.et_identify_code);
		mTvGetIndentifyCode.setTextColor(getResources().getColor(R.color.color_btn_disable));
	}

	private void initData() {

	}

	private void initEvent() {
		mTvGetIndentifyCode.setOnClickListener(this);
		mTvNext.setOnClickListener(this);
		mEtNumber.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				mPhonenumber = s.toString();
				validbutton();
			}
		});
		mEtIdentifyCode.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}
	private void validbutton() {

		String phoneNumber = mEtNumber.getText().toString().trim();
		String verityCode = mEtIdentifyCode.getText().toString().trim();


		if(phoneNumber!=null&&phoneNumber.length()==11){
			mTvGetIndentifyCode.setTextColor(getResources().getColor(R.color.color_light_green));
		}else{
			mTvGetIndentifyCode.setTextColor(getResources().getColor(R.color.color_btn_disable));
		}

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id==R.id.tv_next){
			ValidSmsVerityCode();
		}else if(id==R.id.tv_get_identify_code){
			getVerityCode();
		}

	}

	private void ValidSmsVerityCode() {
		String verityCode = mEtIdentifyCode.getText().toString().trim();
		if (NetworkUtils.isOnline()) {
			if (MeUtil.isMobileNum(mPhonenumber)) {
				if (!MeUtil.isVerify_code_six(verityCode)) {
					if (TextUtils.isEmpty(verityCode)) {
						showToastError("验证码不能为空 ");
					} else {
						//如果不是6位纯数字验证码
						showToastError("验证码不正确，请重新输入");
					}

				} else {
					if (!TextUtils.isEmpty(verityCode)) {
						//验证验证码是否正确
						next(verityCode, mPhonenumber);
					}
				}
			} else {
				if (TextUtils.isEmpty(mPhonenumber)) {
					showToastError("手机号不能为空");
				} else {
					showToastError("请输入正确的手机号");
				}

			}
		} else {
			String errorTips = getString(R.string.connect_disable);
			showToastError(errorTips);
		}
	}

	private void next(final String verityCode, final String phonenumber) {
		MeDao.getInstance().ValidSmsVerityCode( EApplication.BRAND_ID + "", phonenumber, verityCode,
				new BaseExtCallBack(PadRetrievePwdActivity.this) {

					@Override
					public void failed(int errorCode, Object data) {
						if(data!=null){
							if (errorCode == ERR_CODE_ERR) {
								showToastError("验证码不正确，请重新输入!");
							}else{
								showToastError(data.toString());
							}
						}

					}

					@Override
					public void failed(Object data) {
						if (data instanceof NoConnectionError) {
							showToastError( getString(R.string.connect_disable));
						} else if (data instanceof TimeoutError) {
							showToastError("连接超时，请稍后重试");
						}
					}

					@Override
					public void success(Object data) {
						Boolean b = (Boolean) data;
						Intent intent = new Intent(PadRetrievePwdActivity.this, PadReSetPwdActivity.class);
						intent.putExtra("phonenumber", phonenumber);
						intent.putExtra("verityCode", verityCode);
						startActivityForResult(intent, RequestCode.PadResquestCode.REQ_CODE_TO_LOGIN);
					}
				});
	}

	private void getVerityCode() {
		mPhonenumber = mEtNumber.getText().toString();
		if (!MeUtil.isMobileNum(mPhonenumber)) {
			showToastError("请输入正确的手机号");
		} else {
			try {
				if (NetworkUtils.isOnline()) {
					getVerityCodeFromNet(mPhonenumber);
				} else {

					String errorTips = getString(R.string.connect_disable);
					showToastError(errorTips);
				}
			} catch (Exception e) {
				getVerityCodeFromNet(mPhonenumber);
			}

		}
	}

	private void getVerityCodeFromNet(String phonenumber) {
		MeDao.getInstance().getSmsVerityCode( EApplication.BRAND_ID + "", phonenumber, "", "", 3 + "",
				new BaseCallBack() {
					@Override
					public void failed(int errorCode, Object data) {
						if(data==null){
							return;
						}
						if (errorCode == ERR_CODE_BIND_OTHER_PHONE) {
							showToastError("该手机号已绑定其他账号！");
						}else if (errorCode == ERR_CODE_UNBIND) {
							showToastError("该手机号没有绑定账号！");
						}else{
							showToastError(data.toString());
						}
					}

					@Override
					public void failed(Object data) {
						if (data instanceof NoConnectionError) {
							showToastError( getString(R.string.connect_disable));
						} else if (data instanceof TimeoutError) {
							showToastError(getString(R.string.connect_timeout));
						}
					}

					@Override
					public void success(Object data) {
						countdown();
					}
				});




	}

	/**
	 * 吐丝显示错误信息(方块)
	 *
	 * @param msg 字符串
	 */
	public void showToastError(String msg) {
		ToastUtil.INSTANCE.toastInCenter(PadRetrievePwdActivity.this,msg);
	}


	/**
	 * 下发短信按钮倒计时60秒
	 */
	private void countdown() {
		if (currentCount > 0) {
			mTvGetIndentifyCode.setText(currentCount + getResources().getString(R.string.send_message_tips_right));
			mTvGetIndentifyCode.setEnabled(false);
			mHandler.removeMessages(MESSAGE_COUNTDOWN);
			mHandler.sendEmptyMessageDelayed(MESSAGE_COUNTDOWN, 1000);
			currentCount -= 1;
		} else {
			currentCount = 60;
			mTvGetIndentifyCode.setText(getResources().getString(R.string.resend_message_again));
			mTvGetIndentifyCode.setEnabled(true);
		}
	}


	private void hideSoftInputWindow(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null) {
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		}
	}

	public boolean isShouldHideInput(View v, MotionEvent event) {
		if (v != null && (v instanceof EditText)) {
			int[] leftTop = {0, 0};
			//获取输入框当前的location位置
			v.getLocationInWindow(leftTop);
			int left = leftTop[0];
			int top = leftTop[1];
			int bottom = top + v.getHeight();
			int right = left + v.getWidth();
			if (event.getX() > left && event.getX() < right
					&& event.getY() > top && event.getY() < bottom) {
				// 点击的是输入框区域，保留点击EditText的事件
				return false;
			} else {
				return true;
			}
		}
		return false;
	}


	InputMethodManager manager = null;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (manager == null) {
			manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		}
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
				manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}


	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == RequestCode.PadResquestCode.REQ_CODE_TO_LOGIN) {
				setResult(RESULT_OK);
				finish();
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = 0.0f;
		getWindow().setAttributes(lp);
	}

	@Override
	protected void onResume() {
		super.onResume();
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = 1.0f;
		getWindow().setAttributes(lp);

	}
}